//给定一个字符串，验证它是否是回文串，只考虑字母和数字字符，可以忽略字母的大小写。 
//
// 说明：本题中，我们将空字符串定义为有效的回文串。 
//
// 示例 1: 
//
// 输入: "A man, a plan, a canal: Panama"
//输出: true
// 
//
// 示例 2: 
//
// 输入: "race a car"
//输出: false
// 
// Related Topics 双指针 字符串 
// 👍 286 👎 0

package leetcode.editor.cn;

import common.util.MyUtil;

/**
 * Java：验证回文串
 *
 * @author changgui
 */
@SuppressWarnings("all")
public class P125_ValidPalindrome {
    public static void main(String[] args) {
        Solution solution = new P125_ValidPalindrome().new Solution();
//        MyUtil.print(solution.isPalindrome("A man, a plan, a canal: Panama"));
//        MyUtil.print(solution.isPalindrome("race a car"));
        MyUtil.print(solution.isPalindrome("0P"));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public boolean isPalindrome(String s) {
            if (s == null) {
                return false;
            }
            int difference = 'a' - 'A';
            int l = 0, r = s.length() - 1;
            while (l <= r) {
                char lv = s.charAt(l);
                char rv = s.charAt(r);
                if (!match(lv)) {
                    l++;
                    continue;
                }
                if (!match(rv)) {
                    r--;
                    continue;
                }
                if (lv == rv || (!isNum(lv) && !isNum(rv) && Math.abs(lv - rv) == difference)) {
                    l++;
                    r--;
                    continue;
                }
                return false;
            }
            return true;
        }

        private boolean match(char c) {
            return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
        }

        private boolean isNum(char c) {
            return c >= '0' && c <= '9';
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}